import { defineComponent, reactive, ref, toRefs } from 'vue'
import { NForm, NFormItem, NModal, FormRules, NSelect, NButton } from 'naive-ui'
import { Response } from '@/service/modules/common/types'
import { useDatasource } from '../common/use-datasource'
import {
  addOrUpdateDatasourceReq,
  connTestReq
} from '@/service/modules/data-manage'
import { DatasourceInfo } from '@/service/modules/data-manage/types'
import * as FormCard from './datasource-card'

let currentFormCard

const AddDatasourceModal = defineComponent({
  name: 'AddDatasourceModal',
  props: {
    showModal: {
      type: Boolean,
      default: false
    }
  },
  emits: ['modalShowChange', 'refreshList'],
  setup() {
    const state = reactive({
      datasourceForm: {
        name: '',
        description: '',
        datasourceType: null,
        host: '',
        port: '',
        dbName: '',
        username: '',
        password: '',
        other: '',
        driver: '',
        keytabUrl: '',
        krb5ConfUrl: '',
        isSys: false
      },
      formDisabled: ref(true),
      positiveButtonDisabled: ref(false),
      rules: {
        datasourceType: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.datasourceForm.datasourceType === '') {
              return new Error(window.$t('dataManage.datasourceTypeTips'))
            }
          }
        }
      } as FormRules
    })
    //数据源类型下拉选项
    const { dsVariables, getDsTypeOptions } = useDatasource()
    getDsTypeOptions()
    return {
      ...toRefs(state),
      dsVariables
    }
  },
  methods: {
    async onPositiveClick() {
      //输入框存在为空时则确认按钮无效
      if (this.datasourceForm.datasourceType === '' || this.formDisabled) {
        return
      }
      //提交添加数据源请求
      this.positiveButtonDisabled = true
      const res: Response<any> = await addOrUpdateDatasourceReq({
        ...this.datasourceForm
      }).catch(() => {
        this.positiveButtonDisabled = false
      })
      if (res.resp_code === 0) {
        this.initData()
        this.$emit('modalShowChange', false)
        this.$emit('refreshList')
        this.positiveButtonDisabled = false
      } else {
        this.positiveButtonDisabled = false
      }
    },
    onNegativeClick() {
      this.initData()
      this.$emit('modalShowChange', false)
    },
    initData() {
      this.datasourceForm.name = ''
      this.datasourceForm.description = ''
      this.datasourceForm.datasourceType = null
      this.datasourceForm.host = ''
      this.datasourceForm.port = ''
      this.datasourceForm.dbName = ''
      this.datasourceForm.username = ''
      this.datasourceForm.password = ''
      this.datasourceForm.other = ''
      this.datasourceForm.driver = ''
      this.datasourceForm.keytabUrl = ''
      this.datasourceForm.krb5ConfUrl = ''
      this.datasourceForm.isSys = false
    },
    handleFormDataChange(formData: DatasourceInfo, formDisabled: boolean) {
      this.datasourceForm.name = formData.name
      this.datasourceForm.description = formData.description
      this.datasourceForm.host = formData.host
      this.datasourceForm.port = formData.port
      this.datasourceForm.dbName = formData.dbName
      this.datasourceForm.username = formData.username
      this.datasourceForm.password = formData.password
      this.datasourceForm.other = formData.other
      this.datasourceForm.driver = formData.driver
      this.datasourceForm.keytabUrl = formData.keytabUrl
      this.datasourceForm.krb5ConfUrl = formData.krb5ConfUrl
      this.datasourceForm.isSys = formData.isSys

      this.formDisabled = formDisabled
    },
    async onConnTest() {
      connTestReq(this.datasourceForm)
    },
    changeFormCard(value: string) {
      currentFormCard = FormCard[value]
    }
  },
  render() {
    return (
      <NModal
        show={this.showModal}
        mask-closable={false}
        style='width: 400px'
        title={window.$t('dataManage.addDatasource')}
        bordered={false}
        size='huge'
        preset='dialog'
        positive-text={window.$t('dialog.positiveText')}
        negative-text={window.$t('dialog.negativeText')}
        onPositiveClick={this.onPositiveClick}
        onNegativeClick={this.onNegativeClick}
        positiveButtonProps={{
          disabled:
            this.positiveButtonDisabled ||
            this.datasourceForm.datasourceType === '' ||
            this.formDisabled
        }}
        onClose={this.onNegativeClick}
      >
        <NForm
          rules={this.rules}
          label-placement='left'
          require-mark-placement='right-hanging'
          label-width='auto'
        >
          <NFormItem
            path='datasourceType'
            label={window.$t('dataManage.datasourceType')}
          >
            <NSelect
              v-model={[this.datasourceForm.datasourceType, 'value']}
              options={this.dsVariables.dsTypeOptions}
              clearable
              onUpdateValue={this.changeFormCard}
            />
          </NFormItem>
        </NForm>
        <currentFormCard onFormDataChange={this.handleFormDataChange} />
        <NButton onClick={this.onConnTest} type='info' size='small'>
          {window.$t('dataManage.connTest')}
        </NButton>
      </NModal>
    )
  }
})

export default AddDatasourceModal
